import { BASE_URL } from "@/common/config";
import { deepClone, isNull } from "@/common/utils";
import store from "@/store";
let loadingTimer = null;

async function request({
  host = BASE_URL,
  path = "",
  method = "POST",
  responseType = "text",
  contentType = "json",
  params = {},
  showErrorMessage = true, // 接口错误时是否显示提示信息
  header,
}) {
  let url = host + path;
  var token = uni.getStorageSync("token");
  header = {
    ...header,
    token,
  };
  for (const key in header) {
    if (isNull(header[key])) {
      delete header[key];
    }
  }
  const data = deepClone(params);
  for (const key in data) {
    if (isNull(data[key])) {
      delete data[key];
    }
  }

  const options = {
    url,
    header,
    method,
    data,
    responseType,
  };
  if (method.toUpperCase() === "GET" || contentType === "queryString") {
    if (url.indexOf("?") === -1) {
      url += "?";
    }
    for (const key in data) {
      url += `${key}=${data[key]}&`;
    }
    options.url = url;
  }
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success(res) {
        clearTimeout(loadingTimer);
        loadingTimer = null;
        const { code, msg } = res.data;
        if (code !== 200 && showErrorMessage) {
          if (code === 505) {
            uni.removeStorageSync('token');
            var userInfo = store.state.userInfo
            userInfo.isLogin = false;
            store.commit("SET_USER_INFO",userInfo)
          } else {
            console.log(options, res.data);
            uni.showToast({
              title: msg || "网络开小差，请稍后再试。",
              icon: "none",
              duration: 2000,
            });
            res.data.isSuccess = false;
          }
          
        } else {
          res.data.isSuccess = true;
        }
        console.log("request params:", options);
        console.log("request result:", res.data);
        resolve(res.data);
      },
      fail(err) {
        clearTimeout(loadingTimer);
        loadingTimer = null;
        uni.showToast({
          title: "网络开小差，请稍后再试",
          icon: "none",
        });
        reject(err);
      },
    });
  });
}

const API = {
  SCENE_LIST: "/v1/scene/list",
  SCENE_QUESTION_LIST: "/v1/scene/question/list",
  LOGIN_FETCH_PHONE_CODE: "/v1/login/fetch_phone_code",
  LOGIN_PHONE_LOGIN: "/v1/login/phone_login",
  SCENE_ROOM_LIST: "/v1/scene/room/list",
  SCENE_QUESTION_SUBMIT: "/v1/scene/question/submit",
  SCENE_QUESTION_CHECK: "/v1/scene/question/check",
  SCENE_USER_SCORE: "/v1/scene/user/score",
  FETCH_TOKEN: "/v1/login/fetch_token",
};

export { request, API };
